package com.battery.service.impl;

import com.battery.dao.UserDao;
import com.battery.pojo.User;
import com.battery.service.UserService;
import com.battery.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Result addUser(User user) {
        try {
            if(userDao.insertUser(user)>0) {
                return Result.ok().message("添加成功");
            } else
                return Result.error().message("添加失败");
        } catch (DuplicateKeyException e) {
            return Result.error().message("主键重复");
        } catch (Exception e) {
            return Result.error().message("未知错误");
        }
    }

    @Override
    public Result dropUser(int id) {
        try {
            if(userDao.deleteUser(id)>0) {
                return Result.ok().message("删除成功");
            } else
                return Result.error().message("删除失败");
        } catch (Exception e) {
            return Result.error().message("未知错误");
        }
    }

    @Override
    public Result modifyUser(User user) {
        try {
            if(userDao.updateUser(user)>0) {
                return Result.ok().message("修改成功");
            } else
                return Result.error().message("修改失败");
        } catch (Exception e) {
            return Result.error().message("未知错误");
        }
    }

    @Override
    public Result queryUser(int id) {
        try {
            User user = userDao.selectUserById(id);
            if(user == null) {
                return Result.error().message("查询为空");
            } else
                return Result.ok().data("data",user);
        } catch (Exception e) {
            return Result.error().message("未知错误");
        }
    }
}
